package springinpractice.ch1.dao.csv;

import java.math.BigDecimal;
import java.io.*;
import java.util.*;
import java.text.*;
import springinpractice.ch1.model.Account;
import springinpractice.ch1.dao.AccountDao;

/*
 * @author	Willie Wheeler, John Wheeler and Zeeshan Maqbool
 * Book		'Spring In Practice' [Book written by Willie Wheeler and John Wheeler]
 */

public class CsvAccountDao implements AccountDao {
	private String csvFile;

	public void setCsvFile(String csvFile) {
		this.csvFile = csvFile;
	}

	public List<Account> findAll() throws Exception {
		List<Account> results = new ArrayList<Account>();
		DateFormat fmt = new SimpleDateFormat("MMddyyyy");
		BufferedReader br = new BufferedReader(new FileReader(csvFile));
		String line;
		while ((line = br.readLine()) != null) {
			String[] fields = line.split(",");
			String accountNo = fields[0];
			BigDecimal balance = new BigDecimal(fields[1]);
			Date lastPaidOn = fmt.parse(fields[2]);
			Account account = new Account(accountNo, balance, lastPaidOn);
			results.add(account);
		}
		br.close();
		return results;
	}
}
